package org.exaple.mp.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.AllArgsConstructor;
import org.exaple.mp.intercept.QueryInterceptor;
import org.exaple.mp.plugins.CustomPaginationInterceptor;
import org.exaple.mp.props.MybatisPlusProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.Arrays;

/**
 * mybatis-plus 配置
 *
 */
@Configuration
@AllArgsConstructor
@MapperScan("org.example.**.mapper.**")
@EnableConfigurationProperties(MybatisPlusProperties.class)
@PropertySource(value = "classpath:/cloud-mybatis.yml")
public class MybatisPlusConfiguration {

	/**
	 * 分页拦截器
	 */
	@Bean
	public CustomPaginationInterceptor paginationInterceptor(ObjectProvider<QueryInterceptor[]> queryInterceptors,
															 ObjectProvider<ISqlParser[]> sqlParsers,
															 ObjectProvider<ISqlParserFilter> sqlParserFilter,
															 MybatisPlusProperties mybatisPlusProperties) {
		CustomPaginationInterceptor paginationInterceptor = new CustomPaginationInterceptor();
		QueryInterceptor[] queryInterceptorArray = queryInterceptors.getIfAvailable();
		if (ObjectUtils.isNotEmpty(queryInterceptorArray)) {
			AnnotationAwareOrderComparator.sort(queryInterceptorArray);
			paginationInterceptor.setQueryInterceptors(queryInterceptorArray);
		}
		ISqlParser[] sqlParsersArray = sqlParsers.getIfAvailable();
		if (ObjectUtils.isNotEmpty(sqlParsersArray)) {
			paginationInterceptor.setSqlParserList(Arrays.asList(sqlParsersArray));
		}
		paginationInterceptor.setSqlParserFilter(sqlParserFilter.getIfAvailable());
		paginationInterceptor.setLimit(mybatisPlusProperties.getPageLimit());
		return paginationInterceptor;
	}

/*	*//**
	 * sql 日志
	 *//*
	@Bean
	@ConditionalOnProperty(value = "tdii.mybatis-plus.sql-log", matchIfMissing = true)
	public SqlLogInterceptor sqlLogInterceptor() {
		return new SqlLogInterceptor();
	}*/


}

